package com.elitel.common.properties;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;


/**
* Properties 工具类
* @author WWF
*/
public class PropertiesUtil {
	
	
	/**
	 * 加载properties
	 * @param file WEB-INF/classes下
	 * @return
	 */
	public static Properties loadPropertyFile(String file) {
		Properties properties = null;
		
		
		String myPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		//System.out.println(myPath);
		
		if (StringUtils.isEmpty(file)||file.contains("..") ){
			return null;
		}
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		String fullFile; // String fullFile = PathUtil.getWebRootPath() + file;
		if (file.startsWith(File.separator)) // 在Windows下应该这么写：File file1 = new File ("C:\tmp\test.txt");在Linux下则是这样的：File file2 = new File ("/tmp/test.txt");
			fullFile = myPath /*+ File.separator + "WEB-INF"
					+ File.separator + "classes" */+ file;
		else
			fullFile = myPath /*+ File.separator + "WEB-INF"
					+ File.separator + "classes" + File.separator*/ + file;
		//System.out.println(fullFile);
		
		try {
			inputStream = new FileInputStream(new File(fullFile));
			Properties p = new Properties();
			inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
			p.load(inputStreamReader);
			properties = p;
		} catch (FileNotFoundException e) {
			throw new IllegalArgumentException("Properties file not found: "
					+ fullFile);
		} catch (IOException e) {
			throw new IllegalArgumentException(
					"Properties file can not be loading: " + fullFile);
		} finally {
			try {
				if (inputStream != null){
					inputStream.close();
				}
				if (inputStreamReader!=null) {
					inputStreamReader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return properties;
	}
	
}

